package net.xujialiang.XTestRPA.Config.SpringSecurityConfig;

import com.google.gson.Gson;
import net.xujialiang.XTestRPA.Enum.LogEnum;
import net.xujialiang.XTestRPA.Model.ResultData;
import net.xujialiang.XTestRPA.Service.XRPALogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class AdminAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    XRPALogService logService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication auth) throws IOException, ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter printWriter = response.getWriter();

        Map<String, Object> ret = new LinkedHashMap<>();
        SecurityUser user = (SecurityUser) auth.getPrincipal();
        ret.put("token", user.getCurrentUserInfo().getToken());
        Gson gson = new Gson();
        String gsonJson = gson.toJson(ResultData.success(ret));

        printWriter.write(gsonJson);
        printWriter.flush();
        printWriter.close();
        try {
            logService.addLog(LogEnum.Login.getModule(), "登陆成功", user.getUsername(), user.getTTC());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}